package com.bobbyjjw.session;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;

import com.bobbyjjw.common.Common;

/**
 * 获得用户SessionKey
 * 
 * @author Bobby.Jin
 * 
 */

public class GetSessionKey {

	private static String doGetForSessionKey(String address, int port,
			String getParameter) throws Exception {
		String sessionKey = "";
		HttpClient hc = new HttpClient();
		hc.getHostConfiguration().setHost(address, port);
		GetMethod gm = new GetMethod(getParameter);
		hc.executeMethod(gm);
		String result = gm.getResponseBodyAsString();
		if (result != null && result.indexOf("top_appkey=") != -1) {
			int session = result.indexOf("top_session=") + 12;
			sessionKey = result.substring(session, result.substring(session)
					.indexOf("&")
					+ session);
		}
		gm.releaseConnection();
		return sessionKey;
	}

	/**
	 * to Get SessionKey
	 * 
	 * @return
	 */
	public static String getSessionKey(String authCode) {
		String sessionKey = "";
		try {
			sessionKey = doGetForSessionKey(Common.TEST_SESSION_HOST, 80,
					Common.TEST_SESSION_PARAM + authCode);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sessionKey;
	}

	public static void main(String args[]) {
		try {
			String authCode = GetAuthCode.getAuthCode();
			String sessionKey = doGetForSessionKey(Common.TEST_SESSION_HOST,
					80, Common.TEST_SESSION_PARAM + authCode);
			System.out.println(sessionKey);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}